#!/bin/bash
# fastlinux_v0.5_optimized - Linux系统自动化安装和配置脚本 (优化版)
# 代码由ZJY编写，优化版由AI辅助生成

# ========================================================
# 脚本优化说明：
# 1. 代码组织与模块化：重构为函数库、配置分离、消除重复代码
# 2. 性能优化：并行安装、缓存检测结果、大型文件下载优化
# 3. 用户体验优化：进度显示、日志功能、确认与撤销功能
# 4. 功能增强：自动配置环境变量、git、VSCode、Python环境
# 5. 其他改进：错误处理机制、系统备份与恢复、版本检查
# ========================================================

# 配置文件路径
CONFIG_FILE="$HOME/.fastlinux/config.sh"
BACKUP_DIR="$HOME/fastlinux_backups"
LOG_FILE="$HOME/.fastlinux/fastlinux.log"

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # 无颜色

# 全局变量
DISTRO=""
RELEASE=""
CODENAME=""
HAS_DESKTOP=false
SYSTEM_ARCH="$(uname -m)"
PYTHON_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple"
CURRENT_VERSION="0.5"
LATEST_VERSION="0.5"

# 初始化目录和配置
initialize_environment() {
    # 创建配置目录
    mkdir -p "$HOME/.fastlinux"
    mkdir -p "$BACKUP_DIR/sources"
    mkdir -p "$BACKUP_DIR/system"
    
    # 创建日志文件
    touch "$LOG_FILE"
    
    # 记录脚本启动信息
    log "FastLinux v$CURRENT_VERSION 启动，系统：$(uname -a)"
    
    # 创建默认配置文件
    if [ ! -f "$CONFIG_FILE" ]; then
        cat > "$CONFIG_FILE" << EOF
# FastLinux 配置文件
PYTHON_MIRROR="https://pypi.tuna.tsinghua.edu.cn/simple"
DEFAULT_SOURCE="tsinghua"
PARALLEL_INSTALL=true
MAX_PARALLEL_JOBS=4
EOF
    fi
    
    # 加载配置文件
    source "$CONFIG_FILE"
}

# 日志函数
define_log_functions() {
    log() {
        local timestamp="$(date +"%Y-%m-%d %H:%M:%S")"
        local message="$1"
        echo -e "[$timestamp] $message"
        echo "[$timestamp] $message" >> "$LOG_FILE"
    }
    
    log_info() {
        log "${BLUE}信息：$1${NC}"
    }
    
    log_success() {
        log "${GREEN}成功：$1${NC}"
    }
    
    log_warning() {
        log "${YELLOW}警告：$1${NC}"
    }
    
    log_error() {
        log "${RED}错误：$1${NC}"
    }
}

# 错误处理函数
define_error_handling() {
    # 捕获Ctrl+C信号
trap 'log_warning "用户中断操作，程序退出"; exit 1' SIGINT
    
    handle_error() {
        local message="$1"
        local return_code="$2"
        
        log_error "$message"
        
        # 重试/跳过机制改进
        read -p "请选择 (1) 重试 (2) 跳过 (3) 查看详细日志 (4) 退出: " choice
        case $choice in
            1) return 1 ;;  # 重试
            2) return 0 ;;  # 跳过
            3) 
                less "$LOG_FILE"
                handle_error "$message" "$return_code"
                ;;  # 查看日志后重新选择
            4) exit 1 ;;  # 退出
            *) 
                log_warning "无效选择，默认跳过"
                return 0 
                ;;  # 默认跳过
        esac
    }
    
    # 检查命令是否成功执行
    check_command() {
        local cmd_output="$1"
        local return_code="$2"
        local error_message="$3"
        
        if [ "$return_code" -ne 0 ]; then
            log_error "命令执行失败：$error_message"
            if [ -n "$cmd_output" ]; then
                log "错误输出：$cmd_output"
            fi
            return 1
        fi
        return 0
    }
}

# 系统检测函数
define_system_detection() {
    # 检测系统信息（带缓存机制）
    detect_system() {
        # 检查是否有缓存结果
        if [ -f "$HOME/.fastlinux/system_info.cache" ]; then
            log_info "使用缓存的系统信息..."
            source "$HOME/.fastlinux/system_info.cache"
            log_success "系统检测完成: $DISTRO $RELEASE $CODENAME"
            return 0
        fi
        
        log_info "正在检测系统信息..."
        
        # 检测发行版
        if [ -f /etc/os-release ]; then
            . /etc/os-release
            DISTRO="$ID"
            RELEASE="$VERSION_ID"
            CODENAME="$VERSION_CODENAME"
        elif [ -f /etc/redhat-release ]; then
            if grep -qi "centos" /etc/redhat-release; then
                DISTRO="centos"
            elif grep -qi "redhat" /etc/redhat-release; then
                DISTRO="rhel"
            fi
            RELEASE="$(grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | head -1)"
        else
            log_error "无法检测到操作系统类型"
            handle_error "系统检测失败" 1
            return 1
        fi

        # 检测是否有桌面环境
        if [ -n "$DISPLAY" ] || [ -n "$XDG_SESSION_TYPE" ] || pgrep -x "Xorg" > /dev/null; then
            HAS_DESKTOP=true
            log_success "检测到桌面环境"
        else
            HAS_DESKTOP=false
            log_warning "未检测到桌面环境，将在后续步骤中安装"
        fi

        # 缓存检测结果
        cat > "$HOME/.fastlinux/system_info.cache" << EOF
DISTRO="$DISTRO"
RELEASE="$RELEASE"
CODENAME="$CODENAME"
HAS_DESKTOP="$HAS_DESKTOP"
EOF

        log_success "系统检测完成: $DISTRO $RELEASE $CODENAME"
        return 0
    }
    
    # 检查版本更新
    check_version_update() {
        log_info "检查版本更新..."
        
        # 模拟检查更新（实际使用时可从GitHub API获取）
        # 这里简单比较版本号
        if [ "$LATEST_VERSION" != "$CURRENT_VERSION" ]; then
            log_warning "检测到新版本 v$LATEST_VERSION，建议更新到最新版本"
            read -p "是否查看更新详情？(y/n): " show_update
            if [ "$show_update" = "y" ] || [ "$show_update" = "Y" ]; then
                log_info "更新内容：1. 修复了若干bug 2. 增加了新功能 3. 优化了性能"
            fi
        else
            log_success "当前已是最新版本 v$CURRENT_VERSION"
        fi
    }
}

# 源管理函数库
define_source_management() {
    # 源管理主菜单
source_menu() {
    while true; do
        clear
        echo -e "${BLUE}=============================================${NC}"
        echo -e "${CYAN}               源管理菜单                     ${NC}"
        echo -e "${BLUE}=============================================${NC}"
        echo -e "当前系统: ${YELLOW}$DISTRO $RELEASE${NC}"
        echo -e "1. 切换到清华源"
        echo -e "2. 切换到阿里云源"
        echo -e "3. 切换到中科大源"
        echo -e "4. 切换到官方源"
        echo -e "5. 备份当前源配置"
        echo -e "6. 恢复源配置"
        echo -e "7. 配置Python镜像源"
        echo -e "0. 返回主菜单"
        echo -e "${BLUE}=============================================${NC}"
        read -p "请选择操作 [0-7]: " choice

        case $choice in
            1) change_source "tsinghua" && wait_for_enter ;;  # 统一调用函数
            2) change_source "aliyun" && wait_for_enter ;;   # 统一调用函数
            3) change_source "ustc" && wait_for_enter ;;     # 统一调用函数
            4) change_source "official" && wait_for_enter ;; # 统一调用函数
            5) backup_sources && wait_for_enter ;;           # 保持原函数
            6) restore_sources && wait_for_enter ;;          # 保持原函数
            7) configure_python_mirror && wait_for_enter ;;  # 新增函数
            0) break ;;                                      # 返回主菜单
            *) 
                log_error "无效选择，请重试"
                wait_for_enter
                ;;  # 无效输入
        esac
    done
}

    # 统一的源切换函数
    change_source() {
        local source_name="$1"
        local source_url=""
        local source_name_cn=""
        
        # 根据源名称设置参数
        case $source_name in
            "tsinghua")
                source_url="https://mirrors.tuna.tsinghua.edu.cn"
                source_name_cn="清华源"
                ;;
            "aliyun")
                source_url="http://mirrors.aliyun.com"
                source_name_cn="阿里云源"
                ;;
            "ustc")
                source_url="https://mirrors.ustc.edu.cn"
                source_name_cn="中科大源"
                ;;
            "official")
                # 官方源根据发行版设置不同URL
                source_name_cn="官方源"
                ;;
            *)
                log_error "无效的源名称"
                return 1
                ;;
        esac
        
        log_info "正在切换到${source_name_cn}..."
        
        # 先备份当前源
        backup_sources || return 1
        
        # 根据发行版执行不同的源切换逻辑
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            switch_deb_source "$source_name" "$source_url" "$source_name_cn"
        elif [[ $DISTRO == "centos" || $DISTRO == "rhel" ]]; then
            switch_rpm_source "$source_name" "$source_url" "$source_name_cn"
        elif [[ $DISTRO == "fedora" ]]; then
            switch_fedora_source "$source_name" "$source_url" "$source_name_cn"
        else
            log_error "不支持的发行版"
            return 1
        fi
        
        # 清除包缓存
        clear_package_cache
        
        return $?
    }
    
    # Debian/Ubuntu 源切换函数
    switch_deb_source() {
        local source_name="$1"
        local source_url="$2"
        local source_name_cn="$3"
        
        if [ -z "$CODENAME" ]; then
            log_error "无法确定${DISTRO}版本代号"
            return 1
        fi
        
        # 设置源内容
        if [ "$source_name" = "official" ]; then
            # 官方源
            if [ "$DISTRO" = "ubuntu" ]; then
                source_content="# Ubuntu 官方源 $RELEASE ($CODENAME)\ndeb http://archive.ubuntu.com/ubuntu/ $CODENAME main restricted universe multiverse\ndeb http://archive.ubuntu.com/ubuntu/ $CODENAME-updates main restricted universe multiverse\ndeb http://archive.ubuntu.com/ubuntu/ $CODENAME-backports main restricted universe multiverse\ndeb http://security.ubuntu.com/ubuntu/ $CODENAME-security main restricted universe multiverse"
            else
                source_content="# Debian 官方源 $RELEASE ($CODENAME)\ndeb http://deb.debian.org/debian/ $CODENAME main contrib non-free\ndeb http://deb.debian.org/debian/ $CODENAME-updates main contrib non-free\ndeb http://deb.debian.org/debian/ $CODENAME-backports main contrib non-free\ndeb http://security.debian.org/debian-security $CODENAME-security main contrib non-free"
            fi
        else
            # 镜像源
            source_content="# ${source_name_cn} ${DISTRO} $RELEASE ($CODENAME)\ndeb ${source_url}/${DISTRO}/ $CODENAME main restricted universe multiverse\ndeb ${source_url}/${DISTRO}/ $CODENAME-updates main restricted universe multiverse\ndeb ${source_url}/${DISTRO}/ $CODENAME-backports main restricted universe multiverse\ndeb ${source_url}/${DISTRO}-security/ $CODENAME-security main restricted universe multiverse"
        fi
        
        # 写入源文件并更新
        sudo tee /etc/apt/sources.list <<< "$source_content"
        sudo apt update
        
        check_command "" "$?" "切换到${source_name_cn}失败"
        if [ $? -eq 0 ]; then
            log_success "已切换到${source_name_cn}"
            return 0
        else
            return 1
        fi
    }
    
    # CentOS/RHEL 源切换函数
    switch_rpm_source() {
        local source_name="$1"
        local source_url="$2"
        local source_name_cn="$3"
        
        if [ "$DISTRO" = "rhel" ]; then
            log_warning "Red Hat Enterprise Linux 建议使用订阅源，不推荐替换"
            return 1
        fi
        
        # 设置源内容
        if [ "$source_name" = "official" ]; then
            # 官方源
            source_content="[base]\nname=CentOS-\$releasever - Base\nbaseurl=http://mirror.centos.org/centos/\$releasever/os/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever\n\n[updates]\nname=CentOS-\$releasever - Updates\nbaseurl=http://mirror.centos.org/centos/\$releasever/updates/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever\n\n[extras]\nname=CentOS-\$releasever - Extras\nbaseurl=http://mirror.centos.org/centos/\$releasever/extras/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever"
        else
            # 镜像源
            source_content="[base]\nname=CentOS-\$releasever - Base - ${source_name_cn}\nbaseurl=${source_url}/centos/\$releasever/os/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever\n\n[updates]\nname=CentOS-\$releasever - Updates - ${source_name_cn}\nbaseurl=${source_url}/centos/\$releasever/updates/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever\n\n[extras]\nname=CentOS-\$releasever - Extras - ${source_name_cn}\nbaseurl=${source_url}/centos/\$releasever/extras/\$basearch/\ngpgcheck=1\ngpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever"
        fi
        
        # 写入源文件并更新
        sudo tee /etc/yum.repos.d/CentOS-Base.repo <<< "$source_content"
        
        if [[ $DISTRO == "centos" && $RELEASE =~ ^8 ]]; then
            # CentOS 8 需要额外配置PowerTools
            sudo dnf config-manager --set-enabled powertools
        fi
        
        sudo yum clean all && sudo yum makecache
        
        check_command "" "$?" "切换到${source_name_cn}失败"
        if [ $? -eq 0 ]; then
            log_success "已切换到${source_name_cn}"
            return 0
        else
            return 1
        fi
    }
    
    # Fedora 源切换函数
    switch_fedora_source() {
        local source_name="$1"
        local source_url="$2"
        local source_name_cn="$3"
        
        # 设置源内容
        if [ "$source_name" = "official" ]; then
            # Fedora 默认使用官方源，只需清理缓存
            sudo dnf clean all && sudo dnf makecache
        else
            # 镜像源
            source_content="[fedora]\nname=Fedora \$releasever - \$basearch - ${source_name_cn}\nbaseurl=${source_url}/fedora/releases/\$releasever/Everything/\$basearch/os/\nenabled=1\nmetadata_expire=28d\ngpgcheck=1\ngpgkey=${source_url}/fedora/releases/\$releasever/Everything/\$basearch/os/RPM-GPG-KEY-fedora-\$releasever-\$basearch\n\n[updates]\nname=Fedora \$releasever - \$basearch - Updates - ${source_name_cn}\nbaseurl=${source_url}/fedora/updates/\$releasever/\$basearch/\nenabled=1\nmetadata_expire=6h\ngpgcheck=1\ngpgkey=${source_url}/fedora/updates/\$releasever/\$basearch/RPM-GPG-KEY-fedora-\$releasever-\$basearch"
            
            sudo tee /etc/yum.repos.d/fedora.repo <<< "$source_content"
            sudo dnf clean all && sudo dnf makecache
        fi
        
        check_command "" "$?" "切换到${source_name_cn}失败"
        if [ $? -eq 0 ]; then
            log_success "已切换到${source_name_cn}"
            return 0
        else
            return 1
        fi
    }
    
    # 备份源配置
    backup_sources() {
        log_info "正在备份源配置..."
        
        local timestamp="$(date +%Y%m%d_%H%M%S)"
        
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            if [ -f /etc/apt/sources.list ]; then
                sudo cp /etc/apt/sources.list "$BACKUP_DIR/sources/sources.list.$timestamp" && \
                log_success "源配置已备份到 $BACKUP_DIR/sources/sources.list.$timestamp" && return 0
            fi
        elif [[ $DISTRO == "centos" || $DISTRO == "rhel" || $DISTRO == "fedora" ]]; then
            if [ -d /etc/yum.repos.d/ ]; then
                sudo cp -r /etc/yum.repos.d/ "$BACKUP_DIR/sources/yum.repos.d.$timestamp" && \
                log_success "源配置已备份到 $BACKUP_DIR/sources/yum.repos.d.$timestamp" && return 0
            fi
        fi
        
        log_error "备份源配置失败"
        return 1
    }
    
    # 恢复源配置
    restore_sources() {
        log_info "正在恢复源配置..."
        
        if [ ! -d "$BACKUP_DIR/sources" ]; then
            log_error "没有找到备份文件"
            return 1
        fi
        
        log_warning "可用的备份:"
        ls -1 "$BACKUP_DIR/sources" | grep -v '^$'
        
        read -p "请输入要恢复的备份文件名: " backup_file
        local full_path="$BACKUP_DIR/sources/$backup_file"
        
        if [ ! -e "$full_path" ]; then
            log_error "备份文件不存在"
            return 1
        fi
        
        if [[ $backup_file == sources.list.* ]]; then
            sudo cp "$full_path" /etc/apt/sources.list && \
            log_success "源配置已恢复" && return 0
        elif [[ $backup_file == yum.repos.d.* ]]; then
            sudo rm -rf /etc/yum.repos.d/*
            sudo cp -r "$full_path"/* /etc/yum.repos.d/ && \
            log_success "源配置已恢复" && return 0
        else
            log_error "无效的备份文件类型"
            return 1
        fi
    }
    
    # 清除包缓存
    clear_package_cache() {
        log_info "正在清除包缓存..."
        
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt clean
        else
            if [[ $DISTRO == "fedora" ]]; then
                sudo dnf clean all
            else
                sudo yum clean all
            fi
        fi
        
        log_success "包缓存已清除"
        return 0
    }
    
    # 配置Python镜像源
    configure_python_mirror() {
        log_info "正在配置Python镜像源..."
        
        # 创建pip配置目录
        mkdir -p "$HOME/.pip"
        
        # 显示当前镜像源
        if [ -f "$HOME/.pip/pip.conf" ]; then
            current_mirror="$(grep -oP 'index-url = \K.*' "$HOME/.pip/pip.conf" || echo "默认源")"
            log_info "当前Python镜像源: $current_mirror"
        fi
        
        # 选择镜像源
        echo -e "${BLUE}=============================================${NC}"
        echo -e "${CYAN}           Python 镜像源选择                 ${NC}"
        echo -e "${BLUE}=============================================${NC}"
        echo -e "1. 清华源 (https://pypi.tuna.tsinghua.edu.cn/simple)"
        echo -e "2. 阿里云 (https://mirrors.aliyun.com/pypi/simple/)"
        echo -e "3. 中科大 (https://pypi.mirrors.ustc.edu.cn/simple/)"
        echo -e "4. 官方源 (https://pypi.org/simple/)"
        echo -e "5. 自定义源"
        echo -e "${BLUE}=============================================${NC}"
        read -p "请选择镜像源 [1-5]: " choice
        
        case $choice in
            1) pip_mirror="https://pypi.tuna.tsinghua.edu.cn/simple" ;;
            2) pip_mirror="https://mirrors.aliyun.com/pypi/simple/" ;;
            3) pip_mirror="https://pypi.mirrors.ustc.edu.cn/simple/" ;;
            4) pip_mirror="https://pypi.org/simple/" ;;
            5) 
                read -p "请输入自定义镜像源URL: " pip_mirror
                if [ -z "$pip_mirror" ]; then
                    log_error "镜像源URL不能为空"
                    return 1
                fi
                ;;
            *)
                log_error "无效选择，使用默认源"
                pip_mirror="https://pypi.tuna.tsinghua.edu.cn/simple"
                ;;
        esac
        
        # 写入pip配置文件
        cat > "$HOME/.pip/pip.conf" << EOF
[global]
index-url = $pip_mirror
trusted-host = $(echo $pip_mirror | cut -d/ -f3)
[install]
no-cache-dir = true  # 不缓存依赖包（根据用户需求）
EOF
        
        # 更新配置文件中的Python镜像源
        sed -i "s|PYTHON_MIRROR=.*|PYTHON_MIRROR=\"$pip_mirror\"|" "$CONFIG_FILE"
        
        log_success "Python镜像源已配置为: $pip_mirror"
        return 0
    }
}

# 软件安装函数库
define_software_installation() {
    # 安装桌面环境
    install_desktop() {
        if [ "$HAS_DESKTOP" = true ]; then
            log_warning "已检测到桌面环境，无需安装"
            return 0
        fi
        
        log_info "正在安装桌面环境..."
        
        # 显示进度条
        show_progress "准备安装桌面环境" 0
        
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            # 安装GNOME桌面
            sudo apt update && sudo apt install -y ubuntu-desktop || {
                handle_error "安装桌面环境失败" 1
                return $?
            }
            
        elif [[ $DISTRO == "centos" ]]; then
            # 安装GNOME桌面
            sudo yum groupinstall -y "GNOME Desktop" "Graphical Administration Tools" || {
                handle_error "安装桌面环境失败" 1
                return $?
            }
            # 设置默认启动为图形界面
            sudo systemctl set-default graphical.target
            
        elif [[ $DISTRO == "fedora" ]]; then
            # 安装GNOME桌面
            sudo dnf groupinstall -y "Fedora Workstation" || {
                handle_error "安装桌面环境失败" 1
                return $?
            }
            
        elif [[ $DISTRO == "rhel" ]]; then
            # 安装GNOME桌面
            sudo yum groupinstall -y "Server with GUI" || {
                handle_error "安装桌面环境失败" 1
                return $?
            }
            # 设置默认启动为图形界面
            sudo systemctl set-default graphical.target
        fi
        
        show_progress "桌面环境安装完成" 100
        log_success "桌面环境安装完成，建议重启系统"
        
        # 更新桌面环境状态
        HAS_DESKTOP=true
        sed -i "s|HAS_DESKTOP=.*|HAS_DESKTOP=true|" "$HOME/.fastlinux/system_info.cache"
        
        return 0
    }
    
    # 安装软件主函数
    install_software() {
        log_info "正在安装软件..."
        
        # 如果没有桌面环境，先安装
        if [ "$HAS_DESKTOP" = false ]; then
            install_desktop || {
                log_error "无法安装桌面环境，软件安装可能无法完成"
                return 1
            }
        fi
        
        # 根据不同发行版安装软件
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            # 预更新软件源
            sudo apt update
            
            # 并行安装软件（如果启用）
            if [ "$PARALLEL_INSTALL" = true ]; then
                log_info "使用并行安装模式，最大并行任务数: $MAX_PARALLEL_JOBS"
                install_software_parallel_deb
            else
                install_software_sequential_deb
            fi
            
        elif [[ $DISTRO == "centos" || $DISTRO == "fedora" || $DISTRO == "rhel" ]]; then
            # 并行安装软件（如果启用）
            if [ "$PARALLEL_INSTALL" = true ]; then
                log_info "使用并行安装模式，最大并行任务数: $MAX_PARALLEL_JOBS"
                install_software_parallel_rpm
            else
                install_software_sequential_rpm
            fi
        fi
        
        # 自动配置环境（git、VSCode、Python等）
        auto_configure_environments
        
        log_success "软件安装完成"
        return 0
    }
    
    # 并行安装Debian/Ubuntu软件包
    install_software_parallel_deb() {
        # 定义要安装的软件列表
        local software_list=("firefox:Firefox浏览器"
                           "chromium:Chromium浏览器"
                           "libreoffice:LibreOffice办公套件"
                           "vlc:VLC媒体播放器"
                           "audacity:Audacity音频编辑"
                           "gimp:GIMP图像编辑"
                           "inkscape:Inkscape矢量图形编辑"
                           "gcc:GCC编译器"
                           "g++:G++编译器"
                           "git:Git版本控制"
                           "vim:Vim文本编辑器"
                           "htop:htop系统监控"
                           "gparted:GParted分区工具"
                           "terminator:Terminator终端"
                           "filezilla:FileZilla FTP客户端"
                           "keepassxc:KeePassXC密码管理"
                           "flameshot:Flameshot截图工具"
                           "neofetch:系统信息展示工具")
        
        # 创建任务队列
        local task_queue=()
        for software in "${software_list[@]}"; do
            local package="$(echo $software | cut -d: -f1)"
            local name="$(echo $software | cut -d: -f2)"
            task_queue+=("$package:$name")
        done
        
        # 启动并行安装任务
        local running_jobs=0
        local completed_jobs=0
        local total_jobs=${#task_queue[@]}
        
        while [ $completed_jobs -lt $total_jobs ]; do
            # 启动新任务直到达到最大并行数
            while [ $running_jobs -lt $MAX_PARALLEL_JOBS ] && [ ${#task_queue[@]} -gt 0 ]; do
                local task="${task_queue[0]}"
                local package="$(echo $task | cut -d: -f1)"
                local name="$(echo $task | cut -d: -f2)"
                
                # 从队列中移除任务
                task_queue=(${task_queue[@]:1})
                
                # 启动后台任务
                (install_deb_package "$package" "$name" > /dev/null 2>&1) &
                running_jobs=$((running_jobs + 1))
            done
            
            # 检查任务完成情况
            wait -n
            local exit_code=$?
            running_jobs=$((running_jobs - 1))
            completed_jobs=$((completed_jobs + 1))
            
            # 显示进度
            local progress=$((completed_jobs * 100 / total_jobs))
            show_progress "软件安装进度" $progress
        done
        
        # 安装特殊软件（需要按顺序安装的软件）
        install_onlyoffice_deb
        install_vs_code_deb
        install_docker_deb
    }
    
    # 顺序安装Debian/Ubuntu软件包
    install_software_sequential_deb() {
        # 浏览器
        install_deb_package "firefox" "Firefox浏览器"
        install_deb_package "chromium" "Chromium浏览器"
        
        # 办公套件
        install_deb_package "libreoffice" "LibreOffice办公套件"
        install_onlyoffice_deb
        
        # 媒体工具
        install_deb_package "vlc" "VLC媒体播放器"
        install_deb_package "audacity" "Audacity音频编辑"
        install_deb_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_deb_package "gimp" "GIMP图像编辑"
        install_deb_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_deb
        install_deb_package "gcc" "GCC编译器"
        install_deb_package "g++" "G++编译器"
        install_deb_package "git" "Git版本控制"
        install_deb_package "vim" "Vim文本编辑器"
        install_deb_package "vim-gtk3" "增强版Vim编辑器"
        install_docker_deb
        
        # 系统工具
        install_deb_package "htop" "htop系统监控"
        install_deb_package "glances" "glances系统监控"
        install_deb_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_deb_package "terminator" "Terminator终端"
        install_deb_package "filezilla" "FileZilla FTP客户端"
        install_deb_package "keepassxc" "KeePassXC密码管理"
        install_deb_package "flameshot" "Flameshot截图工具"
        install_deb_package "neofetch" "系统信息展示工具"
    }
    
    # 并行安装RPM软件包
    install_software_parallel_rpm() {
        # 定义要安装的软件列表
        local software_list=("firefox:Firefox浏览器"
                           "gcc:GCC编译器"
                           "gcc-c++:G++编译器"
                           "git:Git版本控制"
                           "vim:Vim文本编辑器"
                           "htop:htop系统监控"
                           "gparted:GParted分区工具"
                           "terminator:Terminator终端"
                           "filezilla:FileZilla FTP客户端"
                           "keepassxc:KeePassXC密码管理"
                           "flameshot:Flameshot截图工具"
                           "neofetch:系统信息展示工具")
        
        # 添加特定发行版的软件
        if [[ $DISTRO != "rhel" ]]; then
            software_list+=(
                "chromium:Chromium浏览器"
                "vlc:VLC媒体播放器"
                "audacity:Audacity音频编辑"
                "gimp:GIMP图像编辑"
                "inkscape:Inkscape矢量图形编辑"
                "libreoffice:LibreOffice办公套件"
            )
        fi
        
        # 创建任务队列
        local task_queue=()
        for software in "${software_list[@]}"; do
            local package="$(echo $software | cut -d: -f1)"
            local name="$(echo $software | cut -d: -f2)"
            task_queue+=("$package:$name")
        done
        
        # 启动并行安装任务
        local running_jobs=0
        local completed_jobs=0
        local total_jobs=${#task_queue[@]}
        
        while [ $completed_jobs -lt $total_jobs ]; do
            # 启动新任务直到达到最大并行数
            while [ $running_jobs -lt $MAX_PARALLEL_JOBS ] && [ ${#task_queue[@]} -gt 0 ]; do
                local task="${task_queue[0]}"
                local package="$(echo $task | cut -d: -f1)"
                local name="$(echo $task | cut -d: -f2)"
                
                # 从队列中移除任务
                task_queue=(${task_queue[@]:1})
                
                # 启动后台任务
                (install_rpm_package "$package" "$name" > /dev/null 2>&1) &
                running_jobs=$((running_jobs + 1))
            done
            
            # 检查任务完成情况
            wait -n
            local exit_code=$?
            running_jobs=$((running_jobs - 1))
            completed_jobs=$((completed_jobs + 1))
            
            # 显示进度
            local progress=$((completed_jobs * 100 / total_jobs))
            show_progress "软件安装进度" $progress
        done
        
        # 安装特殊软件（需要按顺序安装的软件）
        if [[ $DISTRO == "rhel" ]]; then
            install_chromium_rhel
        fi
        install_onlyoffice_rpm
        install_vs_code_rpm
        install_docker_rpm
    }
    
    # 顺序安装RPM软件包
    install_software_sequential_rpm() {
        # 浏览器
        install_rpm_package "firefox" "Firefox浏览器"
        if [[ $DISTRO == "rhel" ]]; then
            install_chromium_rhel
        else
            install_rpm_package "chromium" "Chromium浏览器"
        fi
        
        # 办公套件
        install_rpm_package "libreoffice" "LibreOffice办公套件"
        install_onlyoffice_rpm
        
        # 媒体工具
        install_rpm_package "vlc" "VLC媒体播放器"
        install_rpm_package "audacity" "Audacity音频编辑"
        install_rpm_package "smplayer" "SMPlayer视频播放器"
        
        # 图像处理
        install_rpm_package "gimp" "GIMP图像编辑"
        install_rpm_package "inkscape" "Inkscape矢量图形编辑"
        
        # 开发工具
        install_vs_code_rpm
        install_rpm_package "gcc" "GCC编译器"
        install_rpm_package "gcc-c++" "G++编译器"
        install_rpm_package "git" "Git版本控制"
        install_rpm_package "vim" "Vim文本编辑器"
        if [[ $DISTRO == "centos" || $DISTRO == "rhel" ]]; then
            install_rpm_package "vim-enhanced" "增强版Vim编辑器"
        fi
        install_docker_rpm
        
        # 系统工具
        install_rpm_package "htop" "htop系统监控"
        install_rpm_package "glances" "glances系统监控"
        install_rpm_package "gparted" "GParted分区工具"
        
        # 额外软件
        install_rpm_package "terminator" "Terminator终端"
        install_rpm_package "filezilla" "FileZilla FTP客户端"
        install_rpm_package "keepassxc" "KeePassXC密码管理"
        install_rpm_package "flameshot" "Flameshot截图工具"
        install_rpm_package "neofetch" "系统信息展示工具"
    }
    
    # 安装Debian/Ubuntu软件包
    install_deb_package() {
        local package="$1"
        local name="$2"
        
        log_info "正在安装 $name..."
        if ! sudo apt install -y $package; then
            handle_error "$name 安装失败" 1
            return $?
        fi
        log_success "$name 安装完成"
        return 0
    }
    
    # 安装RPM软件包
    install_rpm_package() {
        local package="$1"
        local name="$2"
        
        log_info "正在安装 $name..."
        if [[ $DISTRO == "fedora" ]]; then
            if ! sudo dnf install -y $package; then
                handle_error "$name 安装失败" 1
                return $?
            fi
        else
            if ! sudo yum install -y $package; then
                handle_error "$name 安装失败" 1
                return $?
            fi
        fi
        log_success "$name 安装完成"
        return 0
    }
    
    # 安装VS Code (Debian/Ubuntu)
    install_vs_code_deb() {
        log_info "正在安装 VS Code..."
        
        # 优化下载过程，添加超时和重试机制
        download_with_retry() {
            local url="$1"
            local output="$2"
            local max_retries=3
            local retry_count=0
            
            while [ $retry_count -lt $max_retries ]; do
                if wget -q --timeout=30 --tries=2 "$url" -O "$output"; then
                    return 0
                fi
                retry_count=$((retry_count + 1))
                log_warning "下载失败，正在重试 ($retry_count/$max_retries)..."
                sleep 2
            done
            return 1
        }
        
        # 导入微软GPG密钥
        download_with_retry "https://packages.microsoft.com/keys/microsoft.asc" "microsoft.asc"
        if [ $? -ne 0 ]; then
            log_error "下载微软GPG密钥失败"
            handle_error "VS Code 安装失败" 1
            return 1
        fi
        
        gpg --dearmor < microsoft.asc > packages.microsoft.gpg
        sudo install -o root -g root -m 644 packages.microsoft.gpg /etc/apt/trusted.gpg.d/
        rm -f packages.microsoft.gpg microsoft.asc
        
        # 添加VS Code源
        sudo add-apt-repository "deb [arch=amd64] https://packages.microsoft.com/repos/code stable main"
        
        # 安装VS Code
        sudo apt update
        if ! sudo apt install -y code; then
            handle_error "VS Code 安装失败" 1
            return $?
        fi
        
        log_success "VS Code 安装完成"
        return 0
    }
    
    # 安装VS Code (RPM)
    install_vs_code_rpm() {
        log_info "正在安装 VS Code..."
        
        # 根据架构选择合适的版本
        local vscode_rpm=""
        if [ "$SYSTEM_ARCH" = "x86_64" ]; then
            vscode_rpm="code-latest-x86_64.rpm"
        else
            vscode_rpm="code-latest-${SYSTEM_ARCH}.rpm"
        fi
        
        # 使用wget下载，添加超时和重试机制
        wget -q --timeout=30 --tries=2 https://packages.microsoft.com/yumrepos/vscode/$vscode_rpm
        
        if [[ $DISTRO == "fedora" ]]; then
            if ! sudo dnf install -y ./$vscode_rpm; then
                handle_error "VS Code 安装失败" 1
                rm -f $vscode_rpm
                return $?
            fi
        else
            if ! sudo yum install -y ./$vscode_rpm; then
                handle_error "VS Code 安装失败" 1
                rm -f $vscode_rpm
                return $?
            fi
        fi
        
        rm -f $vscode_rpm
        log_success "VS Code 安装完成"
        return 0
    }
    
    # 安装Docker (Debian/Ubuntu)
    install_docker_deb() {
        log_info "正在安装 Docker..."
        
        # 安装依赖
        sudo apt update
        sudo apt install -y apt-transport-https ca-certificates curl software-properties-common
        
        # 导入Docker GPG密钥
        curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
        
        # 添加Docker源
        sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
        
        # 安装Docker
        sudo apt update
        if ! sudo apt install -y docker-ce docker-ce-cli containerd.io; then
            handle_error "Docker 安装失败" 1
            return $?
        fi
        
        # 将当前用户添加到docker组
        sudo usermod -aG docker $USER
        log_warning "Docker 安装完成，用户已添加到docker组，需重新登录生效"
        return 0
    }
    
    # 安装Docker (RPM)
    install_docker_rpm() {
        log_info "正在安装 Docker..."
        
        # 安装依赖
        if [[ $DISTRO == "fedora" ]]; then
            sudo dnf install -y dnf-plugins-core
        else
            sudo yum install -y yum-utils
        fi
        
        # 添加Docker源
        sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
        
        # 安装Docker
        if [[ $DISTRO == "fedora" ]]; then
            if ! sudo dnf install -y docker-ce docker-ce-cli containerd.io; then
                handle_error "Docker 安装失败" 1
                return $?
            fi
        else
            if ! sudo yum install -y docker-ce docker-ce-cli containerd.io; then
                handle_error "Docker 安装失败" 1
                return $?
            fi
        fi
        
        # 启动Docker服务
        sudo systemctl start docker
        sudo systemctl enable docker
        
        # 将当前用户添加到docker组
        sudo usermod -aG docker $USER
        log_warning "Docker 安装完成，用户已添加到docker组，需重新登录生效"
        return 0
    }
    
    # 在RHEL上安装Chromium
    install_chromium_rhel() {
        log_info "正在安装 Chromium浏览器..."
        
        # 添加EPEL源
        sudo yum install -y epel-release
        
        # 安装Chromium
        if ! sudo yum install -y chromium; then
            handle_error "Chromium浏览器 安装失败" 1
            return $?
        fi
        
        log_success "Chromium浏览器 安装完成"
        return 0
    }
    
    # 安装OnlyOffice (Debian/Ubuntu)
    install_onlyoffice_deb() {
        log_info "正在安装 OnlyOffice办公套件..."
        
        # 检查是否已安装
        if dpkg -l | grep -q onlyoffice; then
            log_warning "OnlyOffice 已安装，跳过安装步骤"
            return 0
        fi
        
        # 下载最新的OnlyOffice DEB包
        local onlyoffice_url="https://github.com/ONLYOFFICE/DesktopEditors/releases/download/v7.2.0/onlyoffice-desktopeditors_7.2.0_amd64.deb"
        wget -q --timeout=30 --tries=2 $onlyoffice_url -O onlyoffice.deb
        
        # 安装
        if ! sudo apt install -y ./onlyoffice.deb; then
            handle_error "OnlyOffice办公套件 安装失败" 1
            rm -f onlyoffice.deb
            return $?
        fi
        
        rm -f onlyoffice.deb
        log_success "OnlyOffice办公套件 安装完成"
        return 0
    }
    
    # 安装OnlyOffice (RPM)
    install_onlyoffice_rpm() {
        log_info "正在安装 OnlyOffice办公套件..."
        
        # 检查是否已安装
        if rpm -qa | grep -q onlyoffice; then
            log_warning "OnlyOffice 已安装，跳过安装步骤"
            return 0
        fi
        
        # 下载最新的OnlyOffice RPM包
        local onlyoffice_url="https://github.com/ONLYOFFICE/DesktopEditors/releases/download/v7.2.0/onlyoffice-desktopeditors-7.2.0.x86_64.rpm"
        wget -q --timeout=30 --tries=2 $onlyoffice_url -O onlyoffice.rpm
        
        # 安装
        if [[ $DISTRO == "fedora" ]]; then
            if ! sudo dnf install -y ./onlyoffice.rpm; then
                handle_error "OnlyOffice办公套件 安装失败" 1
                rm -f onlyoffice.rpm
                return $?
            fi
        else
            if ! sudo yum install -y ./onlyoffice.rpm; then
                handle_error "OnlyOffice办公套件 安装失败" 1
                rm -f onlyoffice.rpm
                return $?
            fi
        fi
        
        rm -f onlyoffice.rpm
        log_success "OnlyOffice办公套件 安装完成"
        return 0
    }
    
    # 自动配置环境（git、VSCode、Python等）
    auto_configure_environments() {
        log_info "正在自动配置开发环境..."
        
        # 配置git
        if command -v git > /dev/null; then
            configure_git
        fi
        
        # 配置VSCode
        if command -v code > /dev/null; then
            configure_vscode
        fi
        
        # 配置Python环境
        configure_python_environment
        
        log_success "开发环境配置完成"
        return 0
    }
    
    # 配置git
    configure_git() {
        log_info "配置Git..."
        
        # 检查是否已配置用户名和邮箱
        local git_user="$(git config --global user.name)"
        local git_email="$(git config --global user.email)"
        
        if [ -z "$git_user" ]; then
            read -p "请输入您的Git用户名: " git_user
            git config --global user.name "$git_user"
        fi
        
        if [ -z "$git_email" ]; then
            read -p "请输入您的Git邮箱: " git_email
            git config --global user.email "$git_email"
        fi
        
        # 设置Git全局配置
        git config --global core.editor "vim"
        git config --global color.ui true
        git config --global pull.rebase false
        
        log_success "Git配置完成，用户: $git_user <$git_email>"
        return 0
    }
    
    # 配置VSCode
    configure_vscode() {
        log_info "配置VSCode..."
        
        # 检查是否以普通用户运行（VSCode配置需要用户权限）
        if [ "$USER" = "root" ]; then
            log_warning "以root用户运行，无法配置VSCode用户设置"
            return 0
        fi
        
        # 安装常用插件
        local plugins=("ms-python.python"
                      "ms-vscode.cpptools"
                      "dbaeumer.vscode-eslint"
                      "esbenp.prettier-vscode"
                      "gruntfuggly.todo-tree"
                      "eamodio.gitlens"
                      "oderwat.indent-rainbow"
                      "ms-azuretools.vscode-docker"
                      "redhat.vscode-yaml"
                      "vscode-icons-team.vscode-icons")
        
        log_info "正在安装VSCode插件..."
        for plugin in "${plugins[@]}"; do
            code --install-extension "$plugin" --force > /dev/null 2>&1
        done
        
        # 创建用户设置文件
        local vscode_settings_dir="$HOME/.config/Code/User"
        mkdir -p "$vscode_settings_dir"
        
        # 写入用户设置
        cat > "$vscode_settings_dir/settings.json" << EOF
{
    "editor.tabSize": 2,
    "editor.insertSpaces": true,
    "editor.detectIndentation": true,
    "editor.renderWhitespace": "all",
    "editor.formatOnSave": true,
    "files.autoSave": "afterDelay",
    "terminal.integrated.fontFamily": "'Fira Code', 'Consolas', 'Monaco', monospace",
    "python.defaultInterpreterPath": "$(which python3 2>/dev/null || echo "")",
    "python.formatting.provider": "black",
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": true,
    "workbench.iconTheme": "vscode-icons",
    "workbench.colorTheme": "Default Dark+"
}
EOF
        
        log_success "VSCode配置完成"
        return 0
    }
    
    # 配置Python环境
    configure_python_environment() {
        log_info "配置Python环境..."
        
        # 检查Python是否已安装
        if ! command -v python3 > /dev/null; then
            log_warning "Python未安装，正在安装..."
            
            if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
                sudo apt install -y python3 python3-pip python3-venv
            else
                if [[ $DISTRO == "fedora" ]]; then
                    sudo dnf install -y python3 python3-pip python3-venv
                else
                    sudo yum install -y python3 python3-pip python3-venv
                fi
            fi
        fi
        
        # 配置pip镜像源（如果尚未配置）
        if [ ! -f "$HOME/.pip/pip.conf" ]; then
            configure_python_mirror
        fi
        
        # 安装常用Python依赖包
        log_info "正在安装常用Python依赖包（从镜像源）..."
        
        local python_packages=("pip" "setuptools" "wheel" "virtualenv" "black" "flake8" "pylint" "requests" "numpy" "pandas" "matplotlib")
        
        # 使用镜像源安装依赖，不使用缓存
        python3 -m pip install --upgrade --no-cache-dir -i $PYTHON_MIRROR "${python_packages[@]}"
        
        if [ $? -eq 0 ]; then
            log_success "Python依赖包安装完成"
        else
            log_error "部分Python依赖包安装失败"
        fi
        
        # 创建默认的虚拟环境目录
        mkdir -p "$HOME/.virtualenvs"
        
        # 添加环境变量到bashrc/zshrc
        update_shell_config
        
        log_success "Python环境配置完成"
        return 0
    }
    
    # 更新shell配置文件
    update_shell_config() {
        local shell_config=""
        
        # 检测当前shell
        if [ -n "$BASH_VERSION" ]; then
            shell_config="$HOME/.bashrc"
        elif [ -n "$ZSH_VERSION" ]; then
            shell_config="$HOME/.zshrc"
        fi
        
        if [ -n "$shell_config" ]; then
            # 添加Python虚拟环境配置
            if ! grep -q "# Python Virtual Environment" "$shell_config"; then
                cat >> "$shell_config" << EOF

# Python Virtual Environment
export WORKON_HOME="$HOME/.virtualenvs"
# 创建虚拟环境的快捷命令
mkvirtualenv() {
    python3 -m venv "$WORKON_HOME/\$1"
    echo "虚拟环境 \$1 已创建在 $WORKON_HOME/\$1"
    echo "使用 'workon \$1' 激活"
}
# 激活虚拟环境的快捷命令
workon() {
    if [ -d "$WORKON_HOME/\$1" ]; then
        source "$WORKON_HOME/\$1/bin/activate"
    else
        echo "未找到虚拟环境: \$1"
        echo "可用的虚拟环境:"
        ls -1 "$WORKON_HOME"
    fi
}
# 退出虚拟环境的快捷命令
deactivate() {
    if [ -n "$VIRTUAL_ENV" ]; then
        command deactivate
    else
        echo "未激活虚拟环境"
    fi
}
EOF
            fi
            
            # 添加其他环境变量
            if ! grep -q "# FastLinux Environment Variables" "$shell_config"; then
                cat >> "$shell_config" << EOF

# FastLinux Environment Variables
export PATH="$HOME/.local/bin:\$PATH"
EOF
            fi
        fi
        
        return 0
    }
}

# 系统优化函数库
define_system_optimization() {
    # 系统优化菜单
    optimization_menu() {
        while true; do
            clear
            echo -e "${BLUE}=============================================${NC}"
            echo -e "${CYAN}               系统优化菜单                   ${NC}"
            echo -e "${BLUE}=============================================${NC}"
            echo -e "1. 基础系统优化（适合所有用户）"
            echo -e "2. 性能优化（提升系统响应速度）"
            echo -e "3. 电源管理优化（延长笔记本电池寿命）"
            echo -e "4. 网络优化（针对国内网络环境）"
            echo -e "5. 桌面环境美化（UI优化）"
            echo -e "6. 一键全面优化（执行以上所有优化）"
            echo -e "7. 系统备份"
            echo -e "8. 系统恢复"
            echo -e "0. 返回主菜单"
            echo -e "${BLUE}=============================================${NC}"
            read -p "请选择操作 [0-8]: " choice

            case $choice in
                1) basic_optimization && wait_for_enter ;;   # 基础优化
                2) performance_optimization && wait_for_enter ;; # 性能优化
                3) power_optimization && wait_for_enter ;;   # 电源优化
                4) network_optimization && wait_for_enter ;; # 网络优化
                5) desktop_optimization && wait_for_enter ;; # 桌面优化
                6) 
                    # 全面优化并显示进度
                    log_info "开始全面优化..."
                    show_progress "全面优化准备中" 0
                    
                    basic_optimization
                    show_progress "基础优化完成" 20
                    
                    performance_optimization
                    show_progress "性能优化完成" 40
                    
                    power_optimization
                    show_progress "电源优化完成" 60
                    
                    network_optimization
                    show_progress "网络优化完成" 80
                    
                    desktop_optimization
                    show_progress "桌面优化完成" 100
                    
                    log_success "全面优化完成"
                    wait_for_enter
                    ;;  # 全面优化
                7) system_backup && wait_for_enter ;;  # 系统备份
                8) system_restore && wait_for_enter ;; # 系统恢复
                0) break ;;  # 返回主菜单
                *) 
                    log_error "无效选择，请重试"
                    wait_for_enter
                    ;;  # 无效输入
            esac
        done
    }
    
    # 基础系统优化
    basic_optimization() {
        log_info "正在进行基础系统优化..."
        
        # 更新系统
        log_info "更新系统..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt update && sudo apt upgrade -y && sudo apt autoremove -y
        else
            if [[ $DISTRO == "fedora" ]]; then
                sudo dnf update -y && sudo dnf autoremove -y
            else
                sudo yum update -y && sudo yum autoremove -y
            fi
        fi
        
        # 配置时区为上海
        log_info "设置时区为上海..."
        sudo timedatectl set-timezone Asia/Shanghai
        
        # 启用NTP时间同步
        log_info "启用时间同步..."
        sudo timedatectl set-ntp true
        
        # 配置中文支持
        log_info "配置中文支持..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt install -y language-pack-zh-hans
        else
            if [[ $DISTRO == "fedora" ]]; then
                sudo dnf install -y langpacks-zh_CN
            else
                sudo yum install -y langpacks-zh_CN
            fi
        fi
        
        log_success "基础系统优化完成"
        return 0
    }
    
    # 性能优化
    performance_optimization() {
        log_info "正在进行性能优化..."
        
        # 安装预加载服务，加速常用程序启动
        log_info "安装预加载服务..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt install -y preload
            sudo systemctl enable preload
            sudo systemctl start preload
        else
            log_warning "预加载服务在当前系统不支持，跳过此步骤"
        fi
        
        # 调整Swappiness
        log_info "调整内存交换策略..."
        if ! grep -q "vm.swappiness=10" /etc/sysctl.conf; then
            echo "vm.swappiness=10" | sudo tee -a /etc/sysctl.conf
            sudo sysctl -p
        fi
        
        # 启用TRIM（针对SSD）
        log_info "启用SSD优化..."
        if [ -f /sys/block/sda/queue/rotational ] && [ $(cat /sys/block/sda/queue/rotational) -eq 0 ]; then
            if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" || $DISTRO == "fedora" ]]; then
                sudo systemctl enable fstrim.timer
                sudo systemctl start fstrim.timer
            fi
        else
            log_warning "未检测到SSD，跳过TRIM设置"
        fi
        
        log_success "性能优化完成"
        return 0
    }
    
    # 电源管理优化
    power_optimization() {
        log_info "正在进行电源管理优化..."
        
        # 安装TLP电源管理工具
        log_info "安装电源管理工具..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt install -y tlp tlp-rdw
            sudo systemctl enable tlp
            sudo systemctl start tlp
        else
            if [[ $DISTRO == "fedora" ]]; then
                sudo dnf install -y tlp tlp-rdw
            else
                sudo yum install -y tlp tlp-rdw
            fi
            sudo systemctl enable tlp
            sudo systemctl start tlp
        fi
        
        log_success "电源管理优化完成"
        return 0
    }
    
    # 网络优化
    network_optimization() {
        log_info "正在进行网络优化..."
        
        # 安装网络加速工具
        log_info "安装网络工具..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            sudo apt install -y net-tools dnsutils
        else
            if [[ $DISTRO == "fedora" ]]; then
                sudo dnf install -y net-tools bind-utils
            else
                sudo yum install -y net-tools bind-utils
            fi
        fi
        
        # 配置国内DNS（添加确认机制）
        log_info "配置国内DNS服务器..."
        read -p "是否配置国内DNS（阿里云和114）？(y/n): " setup_dns
        if [ "$setup_dns" = "y" ] || [ "$setup_dns" = "Y" ]; then
            if [ -f /etc/resolv.conf ]; then
                # 备份当前resolv.conf
                sudo cp /etc/resolv.conf /etc/resolv.conf.bak
                
                # 设置阿里云和114 DNS
                echo "nameserver 223.5.5.5" | sudo tee /etc/resolv.conf > /dev/null
                echo "nameserver 114.114.114.114" | sudo tee -a /etc/resolv.conf > /dev/null
                
                log_success "DNS配置已更新，原配置已备份到/etc/resolv.conf.bak"
            fi
        else
            log_info "跳过DNS配置"
        fi
        
        log_success "网络优化完成"
        return 0
    }
    
    # 桌面环境美化（UI优化）
    desktop_optimization() {
        log_info "正在进行桌面环境美化..."
        
        if [ "$HAS_DESKTOP" = false ]; then
            log_warning "未检测到桌面环境，先安装桌面环境"
            install_desktop || return 1
        fi
        
        # 安装主题和图标
        log_info "安装主题和图标..."
        if [[ $DISTRO == "ubuntu" || $DISTRO == "debian" ]]; then
            # 主题包
            sudo apt install -y numix-gtk-theme numix-icon-theme-circle
            sudo apt install -y arc-theme adapta-gtk-theme
            sudo apt install -y papirus-icon-theme
            sudo apt install -y flat-remix-gnome flat-remix
            # 桌面工具
            sudo apt install -y gnome-tweak-tool gnome-shell-extensions
            sudo apt install -y chrome-gnome-shell
            # 应用启动器
            sudo apt install -y ulauncher
            # 壁纸
            sudo apt install -y variety
            # 字体
            sudo apt install -y fonts-wqy-zenhei fonts-wqy-microhei
            sudo apt install -y fonts-noto fonts-noto-color-emoji
            sudo apt install -y fonts-hack fonts-fira-code
            
        elif [[ $DISTRO == "fedora" ]]; then
            # 主题包
            sudo dnf install -y numix-gtk-theme numix-icon-theme-circle
            sudo dnf install -y arc-theme adapta-gtk-theme
            sudo dnf install -y papirus-icon-theme
            # 桌面工具
            sudo dnf install -y gnome-tweak-tool gnome-shell-extensions
            sudo dnf install -y chrome-gnome-shell
            # 应用启动器
            sudo dnf install -y ulauncher
            # 壁纸
            sudo dnf install -y variety
            # 字体
            sudo dnf install -y wqy-zenhei-fonts wqy-microhei-fonts
            sudo dnf install -y google-noto-emoji-fonts
            sudo dnf install -y hack-fonts fira-code-fonts
        fi
        
        # 配置GNOME扩展
        if [ "$USER" != "root" ]; then
            log_info "配置GNOME扩展..."
            
            # 安装常用扩展
            if command -v gnome-extensions > /dev/null; then
                # 自动安装和启用常用扩展
                install_gnome_extension "user-theme@gnome-shell-extensions.gcampax.github.com"
                install_gnome_extension "dash-to-dock@micxgx.gmail.com"
                install_gnome_extension "openweather-extension@jenslody.de"
                install_gnome_extension "clipboard-indicator@tudmotu.com"
                install_gnome_extension "extensions@abteil.org"
                install_gnome_extension "sound-output-device-chooser@kgshank.net"
            fi
            
            # 设置默认主题
            if command -v gsettings > /dev/null; then
                gsettings set org.gnome.desktop.interface gtk-theme "Arc-Dark"
                gsettings set org.gnome.desktop.interface icon-theme "Papirus-Dark"
                gsettings set org.gnome.desktop.interface font-name "Noto Sans CJK SC Regular 11"
                gsettings set org.gnome.desktop.interface document-font-name "Noto Sans CJK SC Regular 11"
                gsettings set org.gnome.desktop.interface monospace-font-name "Fira Code Regular 11"
                
                # 配置桌面背景
                if [ -f /usr/share/backgrounds/ubuntu-default-greyscale-wallpaper.png ]; then
                    gsettings set org.gnome.desktop.background picture-uri file:///usr/share/backgrounds/ubuntu-default-greyscale-wallpaper.png
                fi
                
                # 配置桌面颜色
                gsettings set org.gnome.desktop.interface color-scheme "prefer-dark"
            fi
        fi
        
        log_success "桌面环境美化完成"
        log_info "您可以使用GNOME优化工具(gnome-tweaks)进一步自定义桌面环境"
        return 0
    }
    
    # 安装GNOME扩展
    install_gnome_extension() {
        local extension_id="$1"
        local user_dir="$HOME/.local/share/gnome-shell/extensions"
        
        # 检查扩展是否已安装
        if [ -d "$user_dir/$extension_id" ]; then
            log_info "扩展 $extension_id 已安装，跳过"
            return 0
        fi
        
        # 由于无法直接从命令行安装扩展，这里提供提示
        log_info "建议安装扩展: $extension_id"
        log_info "请使用GNOME扩展网站 (https://extensions.gnome.org/) 安装"
        
        return 0
    }
    
    # 系统备份函数
    system_backup() {
        log_info "正在执行系统备份..."
        
        # 创建备份目录
        local backup_dir="$BACKUP_DIR/system/$(date +%Y%m%d_%H%M%S)"
        mkdir -p "$backup_dir"
        
        # 备份关键配置
        log_info "备份用户配置文件..."
        mkdir -p "$backup_dir/home_config"
        
        # 备份.bashrc和.zshrc
        if [ -f "$HOME/.bashrc" ]; then
            cp "$HOME/.bashrc" "$backup_dir/home_config/.bashrc.backup"
        fi
        if [ -f "$HOME/.zshrc" ]; then
            cp "$HOME/.zshrc" "$backup_dir/home_config/.zshrc.backup"
        fi
        
        # 备份git配置
        if [ -f "$HOME/.gitconfig" ]; then
            cp "$HOME/.gitconfig" "$backup_dir/home_config/.gitconfig.backup"
        fi
        
        # 备份pip配置
        if [ -f "$HOME/.pip/pip.conf" ]; then
            cp "$HOME/.pip/pip.conf" "$backup_dir/home_config/pip.conf.backup"
        fi
        
        # 备份VSCode配置
        if [ -d "$HOME/.config/Code/User" ]; then
            cp -r "$HOME/.config/Code/User" "$backup_dir/home_config/VSCode"
        fi
        
        # 备份系统配置
        log_info "备份系统关键配置..."
        mkdir -p "$backup_dir/system_config"
        
        # 备份网络配置
        if [ -f /etc/resolv.conf ]; then
            sudo cp /etc/resolv.conf "$backup_dir/system_config/resolv.conf.backup"
        fi
        
        # 备份系统变量配置
        if [ -f /etc/sysctl.conf ]; then
            sudo cp /etc/sysctl.conf "$backup_dir/system_config/sysctl.conf.backup"
        fi
        
        log_success "系统备份完成，备份文件保存在: $backup_dir"
        return 0
    }
    
    # 系统恢复函数
    system_restore() {
        log_info "正在执行系统恢复..."
        
        if [ ! -d "$BACKUP_DIR/system" ]; then
            log_error "没有找到系统备份文件"
            return 1
        fi
        
        log_warning "可用的系统备份:"
        ls -1 "$BACKUP_DIR/system" | grep -v '^$'
        
        read -p "请输入要恢复的备份目录名: " backup_dir
        local full_path="$BACKUP_DIR/system/$backup_dir"
        
        if [ ! -d "$full_path" ]; then
            log_error "备份目录不存在"
            return 1
        fi
        
        # 恢复用户配置
        if [ -d "$full_path/home_config" ]; then
            log_info "恢复用户配置文件..."
            
            # 恢复.bashrc和.zshrc
            if [ -f "$full_path/home_config/.bashrc.backup" ]; then
                cp "$full_path/home_config/.bashrc.backup" "$HOME/.bashrc"
            fi
            if [ -f "$full_path/home_config/.zshrc.backup" ]; then
                cp "$full_path/home_config/.zshrc.backup" "$HOME/.zshrc"
            fi
            
            # 恢复git配置
            if [ -f "$full_path/home_config/.gitconfig.backup" ]; then
                cp "$full_path/home_config/.gitconfig.backup" "$HOME/.gitconfig"
            fi
            
            # 恢复pip配置
            if [ -f "$full_path/home_config/pip.conf.backup" ]; then
                mkdir -p "$HOME/.pip"
                cp "$full_path/home_config/pip.conf.backup" "$HOME/.pip/pip.conf"
            fi
            
            # 恢复VSCode配置
            if [ -d "$full_path/home_config/VSCode" ]; then
                mkdir -p "$HOME/.config/Code"
                cp -r "$full_path/home_config/VSCode" "$HOME/.config/Code/User"
            fi
        fi
        
        # 恢复系统配置
        if [ -d "$full_path/system_config" ]; then
            log_info "恢复系统关键配置..."
            
            # 恢复网络配置
            if [ -f "$full_path/system_config/resolv.conf.backup" ]; then
                sudo cp "$full_path/system_config/resolv.conf.backup" /etc/resolv.conf
            fi
            
            # 恢复系统变量配置
            if [ -f "$full_path/system_config/sysctl.conf.backup" ]; then
                sudo cp "$full_path/system_config/sysctl.conf.backup" /etc/sysctl.conf
                sudo sysctl -p
            fi
        fi
        
        log_success "系统恢复完成，建议注销或重启系统以使更改生效"
        return 0
    }
}

# 界面和用户交互函数库
define_ui_functions() {
    # 显示进度条
    show_progress() {
        local message="$1"
        local progress="$2"
        local width=40
        local filled=$((progress * width / 100))
        local empty=$((width - filled))
        
        # 清除当前行并显示进度条
        printf "\r${CYAN}${message}${NC}: [${GREEN}"  
        printf "%.0s#" $(seq 1 $filled)  
        printf "%.0s " $(seq 1 $empty)  
        printf "${NC}] ${GREEN}%d%%${NC}" $progress  
        
        # 如果进度为100%，换行
        if [ "$progress" -eq 100 ]; then
            echo ""
        fi
    }
    
    # 等待用户输入
    wait_for_enter() {
        read -p "按Enter键继续..." response
    }
    
    # 显示用户须知
    show_disclaimer() {
        clear
        echo -e "${RED}=====================================================${NC}"
        echo -e "${RED}                     重要须知                       ${NC}"
        echo -e "${RED}=====================================================${NC}"
        echo -e "${YELLOW}1. 本脚本需要以root权限运行${NC}"
        echo -e "${YELLOW}2. 脚本会修改系统配置，请确保已备份重要数据${NC}"
        echo -e "${YELLOW}3. 网络环境可能影响脚本执行速度，请确保网络连接稳定${NC}"
        echo -e "${YELLOW}4. 本脚本目前仍处于开发测试阶段(v0.5)${NC}"
        echo -e "${YELLOW}5. 系统优化功能可能因发行版不同而有所差异${NC}"
        echo -e "${RED}=====================================================${NC}"
        wait_for_enter
    }
    
    # 显示系统信息
    show_system_info() {
        echo -e "${CYAN}=============================================${NC}"
        echo -e "${CYAN}                 系统信息                      ${NC}"
        echo -e "${CYAN}=============================================${NC}"
        echo -e "发行版: ${GREEN}$DISTRO${NC}"
        echo -e "版本: ${GREEN}$RELEASE${NC}"
        if [ -n "$CODENAME" ]; then
            echo -e "代号: ${GREEN}$CODENAME${NC}"
        fi
        echo -e "架构: ${GREEN}$SYSTEM_ARCH${NC}"
        echo -e "桌面环境: ${GREEN}$(if [ "$HAS_DESKTOP" = true ]; then echo "已安装"; else echo "未安装"; fi)${NC}"
        echo -e "当前用户: ${GREEN}$USER${NC}"
        echo -e "脚本版本: ${GREEN}v$CURRENT_VERSION${NC}"
        echo -e "${CYAN}=============================================${NC}"
    }
}

# 主菜单函数
define_main_menu() {
    main_menu() {
        while true; do
            clear
            
            # 显示系统信息
            show_system_info
            
            # 主菜单内容
            echo -e "${BLUE}=============================================${NC}"
            echo -e "${CYAN}                  FastLinux                     ${NC}"
            echo -e "${BLUE}=============================================${NC}"
            echo -e "1. 源管理（切换国内源/官方源/备份源配置）"
            echo -e "2. 软件安装（浏览器/办公套件/开发工具等）"
            echo -e "3. 系统优化（基础优化/性能/电源/网络/桌面美化）"
            echo -e "4. 桌面环境安装（安装GNOME桌面环境）"
            echo -e "5. 重新检测系统信息"
            echo -e "0. 退出程序"
            echo -e "${BLUE}=============================================${NC}"
            read -p "请选择操作 [0-5]: " choice
            
            case $choice in
                1) source_menu ;;       # 源管理菜单
                2) install_software ;;  # 软件安装
                3) optimization_menu ;; # 系统优化菜单
                4) install_desktop ;;   # 安装桌面环境
                5) detect_system ;;     # 重新检测系统
                0) 
                    log_info "程序已退出"
                    exit 0
                    ;;  # 退出程序
                *) 
                    log_error "无效选择，请重试"
                    wait_for_enter
                    ;;  # 无效输入
            esac
        done
    }
}

# 主程序入口
define_main_entry() {
    main() {
        # 初始化环境
        initialize_environment
        
        # 定义日志函数
        define_log_functions
        
        # 定义错误处理
        define_error_handling
        
        # 检查root权限
        if [ "$(id -u)" -ne 0 ]; then
            log_error "本脚本需要以root权限运行，请使用sudo命令"
            exit 1
        fi
        
        # 显示用户须知
        show_disclaimer
        
        # 定义系统检测函数
        define_system_detection
        
        # 检测系统
        detect_system || {
            log_error "系统检测失败，程序退出"
            exit 1
        }
        
        # 检查版本更新
        check_version_update
        
        # 定义源管理函数
        define_source_management
        
        # 定义软件安装函数
        define_software_installation
        
        # 定义系统优化函数
        define_system_optimization
        
        # 定义UI函数
        define_ui_functions
        
        # 定义主菜单函数
        define_main_menu
        
        # 启动主菜单
        main_menu
        
        return 0
    }
}

# 调用主函数
define_main_entry
main